package com.zhiwang.planet.ui.my

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.core.app.ActivityCompat
import android.telephony.TelephonyManager
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.event.RegisterEvent
import com.zhiwang.planet.mvp.p.GraphCodePresenter
import com.zhiwang.planet.mvp.p.LoginLogoutPresenter
import com.zhiwang.planet.mvp.p.RegisterPresenter
import com.zhiwang.planet.mvp.v.GraphView
import com.zhiwang.planet.mvp.v.LoginView
import com.zhiwang.planet.mvp.v.RegisterView
import com.zhiwang.planet.mvp.v.SmsCodeView
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.util.*
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.android.synthetic.main.activity_register.toolbar
import org.greenrobot.eventbus.EventBus
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class RegisterActivity : BaseActivity(), SmsCodeView, GraphView, RegisterView, LoginView, MiitHelper.AppIdsUpdater {

    val TAG = "RegisterActivity"
    override fun onLogin(user: User) {
        Toaster.message(R.string.login_success)
        EventBus.getDefault().post(LoginEvent())
        EventBus.getDefault().post(RegisterEvent)
        suicideAfterTransition()
    }

    override fun initInjection() {
        DaggerUserComponent.builder()
                .accountModule(AccountModule(this))
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)

        graphPresenter.graphView = this
        registerPresenter.registerView = this
        registerPresenter.smsCodeView = this
        loginPresenter.loginView = this
    }

    var randomStr: String = Random().nextLong().toString()

    @Inject
    lateinit var registerPresenter: RegisterPresenter

    @Inject
    lateinit var graphPresenter: GraphCodePresenter

    @Inject
    lateinit var loginPresenter: LoginLogoutPresenter

    lateinit var disposable: Disposable

    var isForeground = false

    var accountName: String? = null
    var password: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        setSupportActionBar(toolbar)
//        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//        //不让内容顶到状态栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            val content = (findViewById<ViewGroup>(android.R.id.content)).getChildAt(0)
//            content?.fitsSystemWindows = true
//        }
        AppHelper.setStatusBar(this, false, true)

        //监听各输入变化，设置注册按钮颜色
        observeTextChangeWithTargetButtonEnableStatus(
                arrayOf(
                        phoneEditor,
                        graphCodeEditor,
                        smsCodeEditor,
                        passwordEditor,
                        passwordAgainEditor),
                registerButton)

        getGraphCode(graphCodeEditor)
        disposable = Flowable.interval(90, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (isDestroyed.not())
                        getGraphCode(graphCodeEditor)
                }, {

                }, {

                })

        val spanned = SpannableString(getString(R.string.agree_agreement))
        spanned.setSpan(UrlClickSpan(), 5, 13, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        tvAgreement.text = spanned
        tvAgreement.movementMethod = LinkMovementMethod.getInstance()
        tvAgreement.setTextIsSelectable(false)

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 1200)
        } else getDeviceId()
    }



    var deviceId: String? = null
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getDeviceId() {

        deviceId = "无法获取设备号"
        val telecomManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        deviceId = when {
            Build.VERSION.SDK_INT > Build.VERSION_CODES.P -> {
                // oaid for android 10
                retrieveOAIDForAndroidQ()
                return
            }

            //old deviceid
            TextUtils.isEmpty(telecomManager.deviceId).not() -> {
                if (BuildConfig.DEBUG)
                    Toaster.message("step1${Build.VERSION.SDK_INT}")
                telecomManager.deviceId
            }


            // imei
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> retrieveImeiExcludeMeid(telecomManager)


            //failing
            else -> ""
        }
        deviceId?.apply { TokenManager.saveDevice(this) }
    }


    @SuppressLint("NewApi", "MissingPermission")
    private fun retrieveImeiExcludeMeid(telecomManager: TelephonyManager): String {


        val meid0 = telecomManager.getMeid(0) ?: ""
        val meid1 = telecomManager.getMeid(1) ?: ""

        if (BuildConfig.DEBUG)
            Log.i(TAG, "meids--: 0:->$meid0   1:->$meid1")

        val meid = if (TextUtils.isEmpty(meid0)) meid1 else meid0


        val imei0 = telecomManager.getImei(0)
        val imei1 = telecomManager.getImei(1)

        if (BuildConfig.DEBUG)
            Log.i(TAG, "imeis: 0:->$imei0   1:->$imei1")

        val imei = when {
            TextUtils.isEmpty(meid) -> imei0
            TextUtils.equals(meid, imei0) -> imei1
            else -> imei0
        }
        return imei
    }

    private fun retrieveOAIDForAndroidQ() {
        deviceId = deviceId.plus(" android 10;请尝试退出账号后重新登录")
        MiitHelper(this).getDeviceIds(this)
    }


    override fun OnIdsAvalid(ids: String) {

        deviceId = ids
        deviceId?.apply { TokenManager.saveDevice(this) }
    }

    override fun OnIdsError(msg: String?) {
        deviceId = msg
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1200) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getDeviceId()
            }else Toaster.message(R.string.no_read_phonestate_permission_get_deviceid)
        }

    }

    inner class UrlClickSpan : ClickableSpan() {

        override fun onClick(widget: View?) {

//            if (BuildConfig.DEBUG)
//                Toasty.message("星球服务条款")
            WebViewActivity.load(this@RegisterActivity, Store.USER_AGREEMENT)

        }

        override fun updateDrawState(ds: TextPaint?) {
//            super.updateDrawState(ds)
            ds?.linkColor = Color.TRANSPARENT
            ds?.isUnderlineText = false
        }
    }


    //获取图形验证码
    @NetWorkRequired
    fun getGraphCode(v: View) {
        randomStr = Random().nextLong().toString()
        graphPresenter.getRegisterGraphCode(randomStr)
    }

    //获取短信验证码
    @NetWorkRequired
    fun getSmsCode(v: View) {
        registerPresenter.getRegisterSmsCode(randomStr, graphCodeEditor.text.toString(), phoneEditor.text.toString())
    }


    override fun onRegisterSuccess() {
        Toaster.message(R.string.register_success_message)
        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        val wifiName  = wifiManager.connectionInfo?.ssid?:""
        loginPresenter.login(accountName!!, password!!, deviceId!!,wifiName)
//        suicideAfterTransition()
//        quickStartActivity(LoginActivity::class.java)
    }

    override fun onGraphCodeLoad(b: Bitmap) {
        graphCodeImage.setImageBitmap(b)
    }

    override fun onSmsSend() {
        captchaTextView.start()
        Toaster.message(R.string.message_sms_send)
    }

    fun register(v: View) {
        accountName = phoneEditor.text.toString()
        password = passwordAgainEditor.text.toString()
        //check first
        registerPresenter.register(smsCodeEditor.text.toString(), phoneEditor.text.toString(), passwordAgainEditor.text.toString())
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return super.onSupportNavigateUp()
    }

    override fun onResume() {
        super.onResume()
        isForeground = true
    }

    override fun onStop() {
        super.onStop()
        isForeground = false
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable.dispose()
    }
}
